"""
测试calctree
"""
import math
import numpy
from binarytree import binary_tree
from binarytree import calctree
import json

formulas = [
    '2*(1+3*(1+2))',
    '(3-(2*3+1)*2+2)*2-(3+2*(1+2))',
    '((3-(2*3+1)*2+2)*2-(3+2*(1+2)))*2-1',
    '(((3-(2*3+1)*2+2)*2-(3+2*(1+2))))*3-2*(2-3)',

    '(((3-(2*3+1)*2+2)*2-(3+2*(1+2))))*3-2*(2-3)*(((3-(2*3+1)*2+2)*2-(3+2*(1+2))))*3-2*(2-3)',
    '(((3-(2*3+1)*2+2)*2-(3+2*(1+2))))*3-2*(2-3)+(((3-(2*3+1)*2+2)*2-(3+2*(1+2))))*3-2*(2-3)',
    '(((3-(2*3+1)*2+2)*2-(3+2*(1+2))))*3-2*(2-3)*((3-(2*3+1)*2+2)*2-(3+2*(1+2)))',
    '(((3-(2*3+1)*2+2)*2-(3+2*(1+2))))*3-2*(2-3)-((3-(2*3+1)*2+2)*2-(3+2*(1+2)))',
    '(((3-(2*3+1)*2+2)*2-(3+2*(1+2))))*3-2*(2-3)*2*(2-3)'
]

def save_tree(node,fname):
    with open(fname,"wt",encoding="ascii") as f:
        f.write(json.dumps(node.to_dict()))

def load_tree(fname)->binary_tree.BinaryNode:
    with open(fname,"r",encoding="ascii") as f:
        return binary_tree.BinaryNode(f.read())

cnode = load_tree("e:/Source/test/2223829745872..tree")
print(calctree.calc_calctree(cnode))

def print_binary_calc_tree(formula):
    flist = calctree.parse_formula_to_list(formula)
    if calctree.check_formula_list(flist):
        ftree = calctree.flist_to_binarytree(flist)
        save_tree(ftree,"e:/Source/test/%s.%s"%(id(ftree),".tree"))
        result = calctree.calc_calctree(ftree)
        try:
            result2 = eval(formula)
        except ZeroDivisionError:
            result2 = math.nan
        if result!=result2:
            print(formula,'=',result,result2,result==result2)
        else:
            print(formula,'=',result,result2)

#for i in range(20000):
#    formula = random_formula.random_formula(5)
#    print_binary_calc_tree(formula)

for formula in formulas:
    print_binary_calc_tree(formula)

